#pragma once
#include <functional>
#include <vector>
#include <atomic>
#include <memory>
#include <mutex>

#include "noncopyable.h"
#include "Timestamp.h"
#include "CurrentThread.h"

class Channel;
class Poller;
// 事件循环的类
class EventLoop : noncopyable {
public:
  using Functor = std::function<void()>;
  EventLoop();
  ~EventLoop();

  void loop(); // 开启事件循环
  void quit(); // 退出事件循环

  Timestamp pollReturnTime() const { return m_pollReturnTime; }
  // 当前线程执行的 cb
  void runInLoop(Functor cb);
  void queueInLoop(Functor cb);
  void wakeup();
  void updateChannel(Channel* channel);
  void removeChannel(Channel* channel);
  bool hasChannel(Channel* channel);
  bool isInLoopThread() const { return m_threadId == CurrentThread::tid();}
  uint32_t getlistenCnt() const { return m_listenCnt.load();}
  std::string getHashCode();
  
private:
  void handleRead();
  void doPendingFunctors();
  void printActiveChannels() const; // DEBUG
private:
  using ChannelList = std::vector<Channel*>;
  std::atomic<bool> m_looping;
  std::atomic<bool> m_quit;
  std::atomic<bool> m_callingPendingFunctor;
  Timestamp m_pollReturnTime;
  std::unique_ptr<Poller> m_poller; 
  const pid_t m_threadId; // 记录当前eventloop线程的 id
  // 主要作用唤醒 subloop
  int m_wakeupFd; 

  std::unique_ptr<Channel> m_wakeupChannel;

  ChannelList m_activeChannels;
  Channel* m_currentActiveChannel;
  std::vector<Functor> m_pendingFunctor; // 存储 loop 需要执行的所有回调操作
  std::mutex m_mutex; // 用来保证 m_pendingFunctor 的线程安全

  std::atomic<uint32_t> m_listenCnt;
  std::atomic<size_t> m_pendingTasksCount{0};
};

